package com.springboot.service;

import com.springboot.constant.CommonConstant;
import com.springboot.domain.*;
import com.springboot.dto.*;
import com.springboot.repository.*;
import com.springboot.tools.ResultUtil;
import com.springboot.tools.UUIDTool;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Transactional
@Service
public class BankService {
    private final UserRepository userRepository;
    private final BankRepository bankRepository;
    private final DemandRepository demandRepository;
    private final DemandSubRepository demandSubRepository;
    private final DemandAuthorityRepository demandAuthorityRepository;
    private FileRepository fileRepository;
    private TeamRepository teamRepository;
    private TaskRepository taskRepository;

    @Autowired
    public BankService(BankRepository bankRepository, DemandRepository demandRepository, DemandSubRepository demandSubRepository, DemandAuthorityRepository demandAuthorityRepository, UserRepository userRepository, FileRepository fileRepository, TeamRepository teamRepository, TaskRepository taskRepository) {
        this.userRepository = userRepository;
        this.bankRepository = bankRepository;
        this.demandRepository = demandRepository;
        this.demandSubRepository = demandSubRepository;
        this.demandAuthorityRepository = demandAuthorityRepository;
        this.fileRepository = fileRepository;
        this.teamRepository = teamRepository;
        this.taskRepository = taskRepository;
    }

    public void modify(BankModifyDTO bankRegisterDTO, HttpSession session) {
        String bankId = session.getAttribute("user").toString();
        BtBank btBank = bankRepository.findOne(bankId);
        BeanUtils.copyProperties(bankRegisterDTO, btBank);
        btBank.setStatus(CommonConstant.PASS);
        bankRepository.save(btBank);
    }

    public void addDemand(DemandSubApplyDTO demandSubApplyDTO, HttpSession session) {
        String bankId = session.getAttribute("user").toString();
        BtDemandSub btDemandSub = new BtDemandSub();
        BeanUtils.copyProperties(demandSubApplyDTO, btDemandSub);
        btDemandSub.setBankId(bankId);
        btDemandSub.setId(UUIDTool.getUuid());
        btDemandSub.setDemandId(UUIDTool.getUuid());
        btDemandSub.setCreateTime(new Date());
        btDemandSub.setModifyTime(new Date());
        btDemandSub.setState(CommonConstant.PASS);
        btDemandSub.setOperation(CommonConstant.NEW);
        String files = getStr(demandSubApplyDTO.getFiles());
        btDemandSub.setFileIds(files);
        demandSubRepository.save(btDemandSub);
        Integer outersourcerShow = demandSubApplyDTO.getOutsourcerShown();
        List<String> outsourcerIds = demandSubApplyDTO.getOutsourcerIds();
        // save file
        if (demandSubApplyDTO.getFiles() != null) {
            demandSubApplyDTO.getFiles().forEach(fileId -> {
                fileRepository.update(btDemandSub.getDemandId(), fileId);
            });
        }
        //save demand
        BtDemand btDemand = new BtDemand();
        BeanUtils.copyProperties(btDemandSub, btDemand);
        btDemand.setStatus(CommonConstant.UNSIGNED);
        btDemand.setId(btDemandSub.getDemandId());
        demandRepository.save(btDemand);
        if (outersourcerShow == CommonConstant.DEMAND_PART) {
            for (String id : outsourcerIds) {
                BtDemandAuthority btDemandAuthority = new BtDemandAuthority();
                btDemandAuthority.setId(UUIDTool.getUuid());
                btDemandAuthority.setDemand(btDemand);
                btDemandAuthority.setUserId(id);
                demandAuthorityRepository.save(btDemandAuthority);
            }
        }
    }

    public String getStr(List<String> strList) {
        String resultStr = "";
        if (strList != null && strList.size() > 0) {
            for (int i = 0; i < strList.size(); i++) {
                resultStr = resultStr + strList.get(i) + ',';
            }
            resultStr = resultStr.substring(0, resultStr.length() - 1);
        }
        return resultStr;
    }
    //需求详情与首页查看需求详情（浏览次数）
    public DemandDetailUserDTO demandDetail(String id) {
        BtDemand btDemand = demandRepository.findOne(id);
        DemandDetailUserDTO demandDetailUserDTO = new DemandDetailUserDTO();
        BeanUtils.copyProperties(btDemand, demandDetailUserDTO);
        demandDetailUserDTO.setBankName(bankRepository.findOne(btDemand.getBankId()).getName());
        List<BtFile> files = fileRepository.findByUserId(btDemand.getId());
        demandDetailUserDTO.setFiles(files);
        //需求可以由哪些人查看
        if (btDemand.getOutsourcerShown() == CommonConstant.DEMAND_TOTAL) {
            List<BtUser> btUser1 = userRepository.findByUserType();
            demandDetailUserDTO.setUsers(btUser1);
        } else if (btDemand.getOutsourcerShown() == CommonConstant.DEMAND_PART) {
            List<BtDemandAuthority> btDemandAuthorities = demandAuthorityRepository.findByDemandId(btDemand.getId());
            List<BtUser> btUser2 = new ArrayList<>();
            for (BtDemandAuthority btDemandAuthority : btDemandAuthorities) {
                String userId = btDemandAuthority.getUserId();
                BtUser user = userRepository.findByUserId(userId);
                btUser2.add(user);
            }
            demandDetailUserDTO.setUsers(btUser2);
        }
        int total = btDemand.getViews() + 1;
        demandRepository.addViews(total, btDemand.getId());
        return demandDetailUserDTO;
    }
    //项目详情（需求已签约）todo 浏览次数问题
    public DemandSignedDTO demandSignedDetail(String id) {
        BtDemand btDemand = demandRepository.findOne(id);
        DemandSignedDTO demandSignedDetail = new DemandSignedDTO();
        BeanUtils.copyProperties(btDemand, demandSignedDetail);
        demandSignedDetail.setBankName(bankRepository.findOne(btDemand.getBankId()).getName());
        List<BtFile> files = fileRepository.findByUserId(btDemand.getId());
        demandSignedDetail.setFiles(files);

        List<TeamInfoDTO> allMembers = teamRepository.findTeamByDemandId(btDemand);
        demandSignedDetail.setMembers(allMembers);

//        int total = btDemand.getViews() + 1;
//        demandRepository.addViews(total, btDemand.getId());
        return demandSignedDetail;
    }
    public void demandModify(DemandModifyDTO demandModifyDTO, HttpSession session) {
        List<String> fileIds = demandModifyDTO.getFiles();
        for (String id : fileIds) {
            fileRepository.update(demandModifyDTO.getId(), id);
        }
        String files = getStr(fileIds);
        String demandId = demandModifyDTO.getId();
        BtDemand demand = demandRepository.findOne(demandId);
        BeanUtils.copyProperties(demandModifyDTO, demand);
        demand.setModifyTime(new Date());
        Integer times = demandModifyDTO.getModifyTimes() + 1;
        demand.setModifyTimes(times);
        demand.setFileIds(files);
        demandRepository.save(demand);

        BtDemandSub demandSub = new BtDemandSub();
        BeanUtils.copyProperties(demandModifyDTO, demandSub);
        String bankId = session.getAttribute("user").toString();
//        String bankId = "test";
        demandSub.setId(UUIDTool.getUuid());
        demandSub.setBankId(bankId);
        demandSub.setModifyTime(new Date());
        demandSub.setDemandId(demandId);
        demandSub.setFileIds(files);
        demandSub.setOperation(CommonConstant.MODIFY);
        demandSubRepository.save(demandSub);

        List<String> outsourcerIds = demandModifyDTO.getOutsourcerIds();
        if (demandModifyDTO.getOutsourcerShown() == CommonConstant.DEMAND_PART) {
            demandAuthorityRepository.deleteByDemandId(demandId);

            for (String id : outsourcerIds) {
                BtDemandAuthority btDemandAuthority = new BtDemandAuthority();
                btDemandAuthority.setId(UUIDTool.getUuid());
                btDemandAuthority.setDemand(demand);
                btDemandAuthority.setUserId(id);
                demandAuthorityRepository.save(btDemandAuthority);
            }
        }

    }

    public Result findDetailById(String id) {
        Result<BankDetailsDTO> bankDetails = findBankDetails(id);
        if (!bankDetails.getABoolean()) {
            return bankDetails;
        }
        int total = bankDetails.getData().getViews() + 1;
        bankRepository.addViews(total, bankDetails.getData().getId());
        return bankDetails;
    }

    public Result findBankDetails(String id) {
        BtBank bank = bankRepository.findOne(id);
        if (bank == null) {
            return ResultUtil.error("没有此信息！");
        }
        BankDetailsDTO bankDetailsDTO = new BankDetailsDTO();
        BeanUtils.copyProperties(bank, bankDetailsDTO);
        String ids = fileRepository.findFileId(bank.getId(), "headPicture");
        bankDetailsDTO.setIds(ids);
        return ResultUtil.success(bankDetailsDTO);
    }


    public Result<List<SuRecordDTO>> findBankSuRecord(String bankId) {
        List<SuRecordDTO> list = taskRepository.findBankSuRecord(bankId);
        if (list.size() == 0) {
            return ResultUtil.error("暂无该银行成功交易记录");
        }
        return ResultUtil.success(list);
    }

}
